const { cryptoHelper } = require('./crypto');
const dayjs = require('dayjs');

// 通用工具函数
const helpers = {
    // 加密相关
    cryptoHelper,
    
    // 时间格式化
    formatDateTime: (date) => {
        if (!date) return null;
        return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
    },
    
    formatDate: (date) => {
        if (!date) return null;
        return dayjs(date).format('YYYY-MM-DD');
    },
    
    // 数据验证
    isValidId: (id) => {
        return id && id.toString().trim().length > 0;
    },
    
    isValidString: (str) => {
        return str && str.toString().trim().length > 0;
    },
    
    // 响应格式化
    successResponse: (data, message = '操作成功') => ({
        success: true,
        message,
        data,
        timestamp: new Date().toISOString()
    }),
    
    errorResponse: (message = '操作失败', error = null) => ({
        success: false,
        message,
        error: error?.message || error,
        timestamp: new Date().toISOString()
    }),
    
    // 分页处理
    getPaginationParams: (query) => {
        const page = parseInt(query.page) || 1;
        const limit = parseInt(query.limit) || 10;
        const offset = (page - 1) * limit;
        
        return {
            page: Math.max(1, page),
            limit: Math.min(100, Math.max(1, limit)),
            offset
        };
    },
    
    // 手机号处理
    encryptPhone: (phone) => {
        if (!phone) return null;
        return cryptoHelper.encrypt(phone.toString());
    },
    
    decryptPhone: (encryptedPhone) => {
        if (!encryptedPhone) return null;
        try {
            return cryptoHelper.decrypt(encryptedPhone);
        } catch (error) {
            console.error('手机号解密失败:', error);
            return null;
        }
    },
    
    hashPhone: (phone) => {
        if (!phone) return null;
        return cryptoHelper.hash(phone.toString());
    }
};

module.exports = helpers; 